﻿using Ixxat.Vci3;
using Ixxat.Vci3.Bal;
using Ixxat.Vci3.Bal.Can;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using ListView = System.Windows.Forms.ListView;
using System.IO;
using System.Runtime.InteropServices;

namespace IXXAT
{
    public partial class MainForm : Form
    {
        //参数定义
        #region
        //窗口读取参数表
        private DataTable dtPDO = new DataTable();

        //private int _Count = 0;
        //private string[] _StrName;



        private static bool mConnected = false;
        //IXXAT
        public static IVciDevice mDevIce;//设备名称
        public static ICanMessageWriter mWriter;//写
        public static ICanMessageReader mReader;//读
        public static ICanControl mCanCt1;//Can设备号
        public static ICanChannel mCanChn;//Can通道号
        public static AutoResetEvent mRxEvent;
        public static CanMessage canMessage = new CanMessage();
        //
        public static readonly Int32[] RecBuffer = new int[100];
        public static readonly Int32[] RecBuffer2 = new int[100];
        public static readonly Int32[] RecBuffer22 = new int[100];
        public static readonly Int32[] RecBuffer3 = new int[100];
        //public static Int32[] Rec5ACBuffer = new int[100];
        //ECAN
        private static UInt32 edevtype = 4;

        private UInt32 edevind = 0;
        private UInt32 ecanind = 0;
        //解码处理
        //0X23C
        private static byte[] byteDateBuffer = new byte[4];
        private readonly UInt32[] Int32DataBuffer = new UInt32[4];
        uint Righter = 0;
        uint lefter = 0;
        public static string[] str = new string[100];
        float floatRetain = 0;
        string StrTo2 = "";


        char[] GetVs = new char[100];
        //0X33C
        private static byte[] byte33C = new byte[10];
        private readonly UInt16[] UInt16velocity = new UInt16[4];
        float floatvelocity = 0;


        //0x43C
        private readonly UInt16[] UInt16voltage = new UInt16[4];
        float floatvoltage = 0;
        private readonly Int16[] Int16temperature = new Int16[4];
        public static int Righter1 = 0;
        public static int lefter1 = 0;
        //OX53C        
        char[] DVS = new char[100];
        //0X352
        private static byte[] byte35C = new byte[10];
        private static byte[] b = new byte[4];
        private static Int16[] Int16Motor = new Int16[4];
        private static sbyte[] sbyte35C = new sbyte[10];
        int[] s = new int[4];
        //

        int[] indexs = new int[20];
        private static ThreadStart th23C;
        private static ThreadStart th33C;
        private static ThreadStart th43C;
        private static ThreadStart th53C;
        private static ThreadStart th352;
        //private static ThreadStart th5AC;
        private static ThreadStart thform2;
        private static ThreadStart thform3;
        private static ThreadStart REciveData;
        private static ThreadStart REciveData3;
        //0X5AC
        private readonly int[] recAddress = new int[31];
        public static readonly Int16[] int16resdata = new Int16[31];
        public static readonly UInt16[] uint16resdata = new UInt16[31];
        public static byte[] by = new byte[8];
        //索引表格

        //读取参数表

        #endregion

        //窗体
        #region
        public MainForm()
        {

            InitializeComponent();


        }
        private void Form1_Load(object sender, EventArgs e)
        {
            ////读取参数表
            //dtPDO = Pubclass.ReadCsvToDataTable(Application.StartupPath + @"\Config\PDO数据 - 副本.csv");



            //初始化按钮
            BtnRecord.Enabled = false;
        }
        #endregion

        //AXXAT 初始化
        #region 
        //释放资源
        private static void DisposeVciObject(object obj)
        {
            if (null != obj)
            {
                if (obj is IDisposable dispose)
                {
                    dispose.Dispose();
                }
            }
        }
        private void SelectDevice()//
        {
            IVciDeviceManager deviceManager = null;
            IVciDeviceList deviceList = null;
            IEnumerator deviceEnum = null;

            try
            {
                deviceManager = VciServer.GetDeviceManager();//通过VciServer入口点获取全局设备管理
                deviceList = deviceManager.GetDeviceList();//通过调用该方法获得对全局设备列表的访问权限。如果执行成功，该方法返回对设备列表接口的引用。
                deviceEnum = deviceList.GetEnumerator();//该属性在每次调用时返回一个新设备对象
                deviceEnum.MoveNext();//该方法增加内部索引，以便设备对 象可以返回下一个  CAN  接口卡
                mDevIce = deviceEnum.Current as IVciDevice;
                object serialNumberGuid = mDevIce.UniqueHardwareId;

            }
            catch
            {
            }
            finally
            {
                DisposeVciObject(deviceManager);
                DisposeVciObject(deviceList);
                DisposeVciObject(deviceEnum);
            }
        }
        private bool IXXATStart()//
        {
            IBalObject bal = null;
            bool succeded = false;
            try
            {
                bal = mDevIce.OpenBusAccessLayer();
                mCanChn = bal.OpenSocket(0, typeof(ICanChannel)) as ICanChannel;
                mCanChn.Initialize(1024, 128, false); //此方法初始化CAN通道。
                mReader = mCanChn.GetMessageReader();
                mReader.Threshold = 1;//获取或设置触发器事件的阈值。
                mRxEvent = new AutoResetEvent(false);// 新实例初始化
                mReader.AssignEvent(mRxEvent);//此方法将事件对象分配给消息读取器
                mWriter = mCanChn.GetMessageWriter();//获取对通道的消息编写器对象的新实例的引用。
                mWriter.Threshold = 1;
                mCanChn.Activate();
                mCanCt1 = bal.OpenSocket(0, typeof(ICanControl)) as ICanControl;

                CanBitrate bitrate = new CanBitrate();
                switch (ToolDrpBaudrate.Text)
                {
                    //1000kbps
                    case "1000":
                        bitrate = CanBitrate.Cia1000KBit;
                        break;
                    //800kbps
                    case "800":
                        bitrate = CanBitrate.Cia800KBit;
                        break;
                    //500kbps
                    case "500":
                        bitrate = CanBitrate.Cia500KBit;
                        break;
                    //250kbps
                    case "250":
                        bitrate = CanBitrate.Cia250KBit;
                        break;
                    //125kbps
                    case "125":
                        bitrate = CanBitrate.Cia125KBit;
                        break;
                    //100kbps
                    case "100":
                        bitrate = CanBitrate._100KBit;
                        break;

                    default:
                        bitrate = CanBitrate.Cia125KBit;
                        break;
                }
                mCanCt1.InitLine(CanOperatingModes.Standard | CanOperatingModes.ErrFrame, bitrate);
                mCanCt1.SetAccFilter(CanFilter.Ext, 0x00000C00, 0xFFFFFC01);
                mCanCt1.StartLine();
                succeded = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                DisposeVciObject(bal);
            }
            return succeded;

        }
        private void ToolBtnConnect_Click(object sender, EventArgs e)
        {
            switch (ToolDrpDevType.SelectedIndex)
            {
                case 0:
                    SelectDevice();
                    mConnected = IXXATStart();
                    break;
                case 1:
                    mConnected = ECANStart();
                    break;
            }
            if (!mConnected)
            {
                //连接失败
                string msg = TargetClass.GetDiag.Language == TargetClass.CHS ? "通讯设备连接失败，请检查原因" : "Communicate connect failed，please check the reason";
                string info = TargetClass.GetDiag.Language == TargetClass.CHS ? "警告" : "Warning";
                MessageBox.Show(msg, info, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                return;
            }
            ToolDrpBaudrate.Enabled = !mConnected;
            ToolDrpDevType.Enabled = !mConnected;
            ToolBtnConnect.Enabled = !mConnected;
            ToolBtnDisConnect.Enabled = mConnected;
            timer_rec.Enabled = mConnected;//开始监控


            REciveData = new ThreadStart(IXXATReceiveData1);//通过ThreadStart委托告诉子线程执行什么方法　　
            Thread REcive1 = new Thread(REciveData);
           // REcive1.Start();//启动新线程
            REcive1.IsBackground = true;

            REciveData = new ThreadStart(IXXATReceiveData2);//通过ThreadStart委托告诉子线程执行什么方法　　
            Thread REcive2 = new Thread(REciveData);
            REcive2.Start();//启动新线程
            REcive2.IsBackground = true;

            REciveData = new ThreadStart(IXXATReceiveData3);//通过ThreadStart委托告诉子线程执行什么方法　　
            Thread REcive3 = new Thread(REciveData);
            REcive3.Start();//启动新线程
            REcive3.IsBackground = true;

            toolStripDevStatus.Text = TargetClass.GetDiag.Language == TargetClass.CHS ? "已连接" : "Connected";
            toolStripDevStatus.ForeColor = Color.Lime;
            BtnRecord.Enabled = true;
        }

        private bool IXXATClose()
        {
            try
            {
                DisposeVciObject(mReader);  // Dispose message read
                DisposeVciObject(mWriter);  // Dispose message writer
                DisposeVciObject(mCanChn);  // Dispose CAN channel
                DisposeVciObject(mCanCt1);  // Dispose CAN controller
                DisposeVciObject(mDevIce);  // Dispose VCI device
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion

        //IXXATSend
        #region
        public bool DatatoSend(uint sID, byte[] sData)
        {
            bool res = false;
            switch (ToolDrpDevType.SelectedIndex)
            {
                case 0:
                    res = IXXATSend(sID, sData);
                    break;

            }
            return res;
        }

        byte[] vs = { 0x42, 0x4E, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00 };
        private void BtnSendData_Click(object sender, EventArgs e)
        {
            DatatoSend(0x62C, vs);
        }
        #region
        public bool IXXATSend(uint sID, byte[] sData)
        {
            if (!mConnected) return false;
            bool res = false;
            CanMessage canMsg = new CanMessage
            {
                TimeStamp = 0,
                Identifier = sID,
                FrameType = CanMsgFrameType.Data,
                DataLength = 8,
                SelfReceptionRequest = true  // show this message in the console window
            };
            for (Byte i = 0; i < canMsg.DataLength; i++)
            {
                canMsg[i] = sData[i];
            }
            // Write the CAN message into the transmit FIFO

            if (mWriter.SendMessage(canMsg))
            {
                canMsg.Clear();
                res = true;
            }

            return res;
        }
        #endregion
        #endregion

        //ECan
        #region

        //ECANStart
        #region
        unsafe private bool ECANStart()
        {
            try
            {
                ECANDLL.VCI_CloseDevice(edevtype, edevind);
                edevtype = 4;
                edevind = 0;
                ecanind = 0;
                if (ECANDLL.VCI_OpenDevice(edevtype, edevind, 0) == 0) return false;
                //初始化CAN通信  VCI_INIT_CONFIG
                VCI_INIT_CONFIG config = new VCI_INIT_CONFIG
                {
                    AccCode = 0xC0000000,
                    AccMask = 0x001FFFFF,
                    Filter = 1,
                    Mode = 0,
                };
                switch (ToolDrpBaudrate.SelectedIndex)
                {
                    #region baudrate

                    //1000kbps
                    case 0:
                        config.Timing0 = 0x00;
                        config.Timing1 = 0x14;
                        break;
                    //800kbps
                    case 1:
                        config.Timing0 = 0x00;
                        config.Timing1 = 0x16;
                        break;
                    //500kbps
                    case 2:
                        config.Timing0 = 0x00;
                        config.Timing1 = 0x1C;
                        break;
                    //250kbps
                    case 3:
                        config.Timing0 = 0x01;
                        config.Timing1 = 0x1C;
                        break;
                    //125kbps
                    case 4:
                        config.Timing0 = 0x03;
                        config.Timing1 = 0x1C;
                        break;
                    //100kbps
                    case 5:
                        config.Timing0 = 0x04;
                        config.Timing1 = 0x1C;
                        break;
                    //50kbps
                    case 6:
                        config.Timing0 = 0x09;
                        config.Timing1 = 0x1C;
                        break;
                    //20kbps
                    case 7:
                        config.Timing0 = 0x18;
                        config.Timing1 = 0x1C;
                        break;
                    //10kbps
                    case 8:
                        config.Timing0 = 0x31;
                        config.Timing1 = 0x1C;
                        break;
                    //5kbps
                    case 9:
                        config.Timing0 = 0xBF;
                        config.Timing1 = 0xFF;
                        break;

                        #endregion baudrate
                }

                ECANDLL.VCI_InitCAN(edevtype, edevind, ecanind, ref config);
                ECANDLL.VCI_StartCAN(edevtype, edevind, ecanind);
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion

        //ECANClose
        #region
        private bool ECANClose()
        {
            try
            {
                ECANDLL.VCI_CloseDevice(edevtype, edevind);
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion

        //ECANSend
        #region
        unsafe private bool ECANSend(uint sID, byte[] sData)
        {
            bool res = false;

            VCI_CAN_OBJ sobj = new VCI_CAN_OBJ
            {
                SendType = 0x00,//发送类型 0：正常发送1：只发 2：自发自收
                RemoteFlag = 0x00,// 0x00：数据帧，0x01：远程帧
                ExternFlag = 0x00,// 0x00：标志帧，0x01：扩展帧
                ID = sID,
                DataLen = 8// 数据帧长度：8个字节
            };
            for (int i = 0; i < sobj.DataLen; i++)
            {
                sobj.Data[i] = sData[i];
            }
            if (ECANDLL.VCI_Transmit(edevtype, edevind, ecanind, ref sobj, 1) == 1)
            {
                ECANDLL.VCI_ClearBuffer(edevtype, edevind, ecanind);
                res = true;
            }
            return res;
        }
        #endregion

        //ECANReceiveData
        #region
        unsafe private void ECANReceiveData()
        {
            UInt32 res = new UInt32();
            res = ECANDLL.VCI_GetReceiveNum(edevtype, edevind, ecanind);
            if (res == 0)
                return;
            UInt32 con_maxlen = 50;
            IntPtr pt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(VCI_CAN_OBJ)) * (Int32)con_maxlen);
            res = ECANDLL.VCI_Receive(edevtype, edevind, ecanind, pt, con_maxlen, 100);
            for (UInt32 i = 0; i < res; i++)
            {
                VCI_CAN_OBJ obj = (VCI_CAN_OBJ)Marshal.PtrToStructure((IntPtr)((UInt32)pt + i * Marshal.SizeOf(typeof(VCI_CAN_OBJ))), typeof(VCI_CAN_OBJ));
                RecBuffer[0] = (int)obj.ID;
                if (obj.RemoteFlag == 0)
                {
                    byte len = (byte)(obj.DataLen % 9);
                    for (byte j = 0; j < len; j++)
                    {
                        RecBuffer[j + 1] = obj.Data[j];
                    }
                    ReceiveMsgAnalyse(RecBuffer);
                }
            }
            Marshal.FreeHGlobal(pt);
        }
        #endregion
        #endregion

        //接收 显示
       
        #region
        private void IXXATReceiveData()
        {
            Console.WriteLine("12321");
            mReader.ReadMessage(out canMessage);

            if (canMessage.FrameType == CanMsgFrameType.Data)
            {

                if (!canMessage.RemoteTransmissionRequest)
                {
                    switch ((int)canMessage.Identifier)
                    {
                        case 1452:
                            {
                                RecBuffer[0] = (int)canMessage.Identifier;
                                for (int i = 0; i < canMessage.DataLength; i++)
                                {
                                    RecBuffer[i + 1] = canMessage[i];
                                }

                                ReceiveMsgAnalyse2(RecBuffer);
                                break;
                            }
                        case 572:
                            {
                                RecBuffer[0] = (int)canMessage.Identifier;
                                for (int i = 0; i < canMessage.DataLength; i++)
                                {
                                    RecBuffer[i + 1] = canMessage[i];
                                }
                                ReceiveMsgAnalyse(RecBuffer);
                                break;
                            }
                        case 828:
                            {
                                RecBuffer[0] = (int)canMessage.Identifier;
                                for (int i = 0; i < canMessage.DataLength; i++)
                                {
                                    RecBuffer[i + 1] = canMessage[i];
                                }
                                ReceiveMsgAnalyse(RecBuffer);
                                break;

                            }
                        case 1084:
                            {
                                RecBuffer[0] = (int)canMessage.Identifier;
                                for (int i = 0; i < canMessage.DataLength; i++)
                                {
                                    RecBuffer[i + 1] = canMessage[i];
                                }
                                ReceiveMsgAnalyse(RecBuffer);
                                break;
                            }
                        case 1340:
                            {
                                RecBuffer[0] = (int)canMessage.Identifier;
                                for (int i = 0; i < canMessage.DataLength; i++)
                                {
                                    RecBuffer[i + 1] = canMessage[i];
                                }
                                ReceiveMsgAnalyse(RecBuffer);
                                break;
                            }
                        case 850:
                            {
                                RecBuffer[0] = (int)canMessage.Identifier;
                                for (int i = 0; i < canMessage.DataLength; i++)
                                {
                                    RecBuffer[i + 1] = canMessage[i];
                                }
                                ReceiveMsgAnalyse(RecBuffer);
                                break;
                            }

                    }
                }
            }

        }
        private void IXXATReceiveData1()
        {
            while (true)
            {
                mReader.ReadMessage(out canMessage);
                if (canMessage.FrameType == CanMsgFrameType.Data)
                {
                    if (!canMessage.RemoteTransmissionRequest)
                    {
                        switch ((int)canMessage.Identifier)
                        {
                            case 0x5AC:
                                {
                                    RecBuffer2[0] = (int)canMessage.Identifier;
                                    for (int i = 0; i < canMessage.DataLength; i++)
                                    {
                                        RecBuffer2[i + 1] = canMessage[i];
                                    }
                                    ReceiveMsgAnalyse1(RecBuffer2);
                                    break;
                                }
                        }
                    }
                }
            }
        }


        private void IXXATReceiveData2()
        {
            Console.WriteLine("sewdwdwd");
            while (true)
            {
                mReader.ReadMessage(out canMessage);
                if (canMessage.FrameType == CanMsgFrameType.Data)
                {
                    if (!canMessage.RemoteTransmissionRequest)
                    {
                        switch ((int)canMessage.Identifier)
                        {
                            case 0x5AC:
                                {
                                    RecBuffer22[0] = (int)canMessage.Identifier;
                                    for (int i = 0; i < canMessage.DataLength; i++)
                                    {
                                        RecBuffer22[i + 1] = canMessage[i];
                                    }
                                    ReceiveMsgAnalyse2(RecBuffer22);
                                    break;
                                }
                        }
                    }
                }
            }
        }
        private void IXXATReceiveData3()
        {
            while (true)
            {
                mReader.ReadMessage(out canMessage);
                if (canMessage.FrameType == CanMsgFrameType.Data)
                {
                    if (!canMessage.RemoteTransmissionRequest)
                    {
                        switch ((int)canMessage.Identifier)
                        {
                            case 0x5AC:
                                {
                                    RecBuffer3[0] = (int)canMessage.Identifier;
                                    for (int i = 0; i < canMessage.DataLength; i++)
                                    {
                                        RecBuffer3[i + 1] = canMessage[i];
                                    }
                                    ReceiveMsgAnalyse3(RecBuffer3);
                                    break;
                                }
                        }
                    }
                }
            }
        }
        #endregion

        //解码方法
        #region
        private void MsgAnalyse1()
        {
            //第一个数
            byteDateBuffer[0] = Convert.ToByte(RecBuffer[1]);

            //第二个数
            Int32DataBuffer[1] = Convert.ToUInt16((RecBuffer[5] * 256 + RecBuffer[4]));
            Int32DataBuffer[0] = Convert.ToUInt16((RecBuffer[3] * 256 + RecBuffer[2]));
            Righter = Int32DataBuffer[0] & 0xffff;//低十六位
            lefter = Int32DataBuffer[1] & 0xffff; //高十六位                       
            lefter <<= 16;
            lefter |= Convert.ToUInt32(Righter);
            floatRetain = (float)(lefter * 0.1);

            //第三个数
            byteDateBuffer[1] = Convert.ToByte(RecBuffer[6]);

            //第四个数
            StrTo2 = Convert.ToString(RecBuffer[7], 2).PadLeft(8, '0');
            GetVs = StrTo2.ToCharArray();
            str[1] = byteDateBuffer[0].ToString("0.##");
            str[2] = floatRetain.ToString("0.##");
            str[3] = byteDateBuffer[1].ToString("0.##");
            str[4] = Convert.ToString(GetVs[7]);
            str[5] = Convert.ToString(GetVs[6]);
            str[6] = Convert.ToString(GetVs[5]);
            //

            //预留 6个
        }
        private void MsgAnalyse2()
        {
            //第一个数
            byte33C[0] = 0;
            //第二个数
            byte33C[1] = 0;
            //第三个数
            byte33C[2] = Convert.ToByte(RecBuffer[3]);
            //第四个数
            UInt16velocity[0] = Convert.ToUInt16(RecBuffer[5] * 256 + RecBuffer[4]);
            floatvelocity = (float)(UInt16velocity[0] * 0.1);
            //第五个数
            UInt16velocity[1] = Convert.ToUInt16(RecBuffer[7] * 256 + RecBuffer[6]);
            //预留
            byte33C[3] = 0;
            str[8] = byte33C[2].ToString("0.##");
            str[9] = floatvelocity.ToString("0.##");
            str[10] = UInt16velocity[1].ToString("0.##");


        }
        private void MsgAnalyse3()
        {
            //第一个数
            UInt16voltage[0] = Convert.ToUInt16(RecBuffer[2] * 256 + RecBuffer[1]);
            floatvoltage = (float)(UInt16voltage[0] * 0.1);
            //第二个数
            Righter1 = RecBuffer[3] & 0xff;//低八位
            lefter1 = RecBuffer[4] & 0xff; //高八位
            Int16temperature[0] = Convert.ToInt16(lefter1);
            Int16temperature[0] <<= 8;
            Int16temperature[0] |= Convert.ToInt16(Righter1);
            //第三个数                        
            Righter1 = RecBuffer[5] & 0xff;//低八位
            lefter1 = RecBuffer[6] & 0xff; //高八位
            Int16temperature[1] = Convert.ToInt16(lefter1);
            Int16temperature[1] <<= 8;
            Int16temperature[1] |= Convert.ToInt16(Righter1);
            //第四个数
            Righter1 = RecBuffer[7] & 0xff;//低八位
            lefter1 = RecBuffer[8] & 0xff; //高八位
            Int16temperature[2] = Convert.ToInt16(lefter1);
            Int16temperature[2] <<= 8;
            Int16temperature[2] |= Convert.ToInt16(Righter1);
            str[12] = floatvoltage.ToString("0.##");
            str[13] = Int16temperature[0].ToString("0.##");
            str[14] = Int16temperature[1].ToString("0.##");
            str[15] = Int16temperature[2].ToString("0.##");
            //


        }
        private void MsgAnalyse4()
        {
            //第一个数                        
            byteDateBuffer[2] = Convert.ToByte(RecBuffer[1]);
            //第二个数
            StrTo2 = Convert.ToString(RecBuffer[2], 2).PadLeft(8, '0');
            DVS = StrTo2.ToCharArray();
            str[17] = byteDateBuffer[2].ToString("0.##");
            str[18] = Convert.ToString(DVS[7]);
            str[19] = Convert.ToString(DVS[6]);
            str[20] = Convert.ToString(DVS[5]);
            str[21] = Convert.ToString(DVS[4]);
            str[22] = Convert.ToString(DVS[3]);
            str[23] = Convert.ToString(DVS[2]);
            //

        }
        private void MsgAnalyse5()
        {
            //第一个数
            byte35C[0] = Convert.ToByte(RecBuffer[1]);
            //第二个数                                              
            //第三个数
            byte35C[2] = Convert.ToByte(RecBuffer[3]);
            //第四个数
            byte35C[3] = Convert.ToByte(RecBuffer[4]);
            s[0] = Convert.ToByte(byte35C[3]) - 55;
            //第五个数
            byte35C[4] = Convert.ToByte(RecBuffer[5]);
            s[1] = Convert.ToByte(byte35C[4]) - 55;
            //第六个数                      
            Righter1 = RecBuffer[6] & 0xff;//低八位
            lefter1 = RecBuffer[7] & 0xff; //高八位
            Int16Motor[0] = Convert.ToInt16(lefter1);
            Int16Motor[0] <<= 8;
            Int16Motor[0] |= Convert.ToInt16(Righter1);
            str[25] = Convert.ToString(byte35C[0]);
            str[26] = Convert.ToString(byte35C[2]);
            str[27] = Convert.ToString(s[0]);
            str[28] = Convert.ToString(s[1]);
            str[29] = Convert.ToString(Int16Motor[0]);
            //

        }

        public static void MsgAnalyse6()
        {
            //42 4E 40 00
            str[34] = RecBuffer22[1].ToString("X");

            str[35] = RecBuffer22[2].ToString("X");
            str[36] = RecBuffer22[3].ToString("X");
            str[37] = RecBuffer22[4].ToString("X");
            //F1 B8 F3 C2
            str[30] = RecBuffer22[5].ToString("X");

            str[31] = RecBuffer22[6].ToString("X");

            str[32] = RecBuffer22[7].ToString("X");

            str[33] = RecBuffer22[8].ToString("X");


        }
      
        #endregion

        //解码处理
        #region

        private void ReceiveMsgAnalyse(object data)
        {

            switch (RecBuffer[0])
            {
                case 0x23C:
                    {
                        th23C = new ThreadStart(MsgAnalyse1);//通过ThreadStart委托告诉子线程执行什么方法　　
                        Thread thread1 = new Thread(th23C);
                        thread1.Start();//启动新线程

                        break;
                    }
                case 0x33C:
                    {
                        //th33C = new ThreadStart(MsgAnalyse2);//通过ThreadStart委托告诉子线程执行什么方法　　
                        //Thread thread2 = new Thread(th33C);
                        //thread2.Start();//启动新线程
                        MsgAnalyse2();

                        break;
                    }
                case 0x43C:
                    {
                        th43C = new ThreadStart(MsgAnalyse3);//通过ThreadStart委托告诉子线程执行什么方法　　
                        Thread thread3 = new Thread(th43C);
                        thread3.Start();//启动新线程

                        break;

                    }
                case 0x53C:
                    {
                        th53C = new ThreadStart(MsgAnalyse4);//通过ThreadStart委托告诉子线程执行什么方法　　
                        Thread thread4 = new Thread(th53C);
                        thread4.Start();//启动新线程
                        ;
                        break;
                    }
                case 0x352:
                    {
                        th352 = new ThreadStart(MsgAnalyse5);//通过ThreadStart委托告诉子线程执行什么方法　　
                        Thread thread5 = new Thread(th352);
                        thread5.Start();//启动新线程

                        break;
                    }
                //case 0x5AC:
                //    {

                //        //连接
                //        if (RecBuffer[1] == 66 && RecBuffer[2] == 78 && RecBuffer[3] == 64 && RecBuffer[4] == 0 && RecBuffer[5] == 241 && RecBuffer[6] == 184 && RecBuffer[7] == 243 && RecBuffer[8] == 194)
                //        {
                //            MsgAnalyse6();
                //            break;
                //        }
                //        if (RecBuffer[1] == 96 && RecBuffer[2] == MainForm2.low[MainForm2.row] && RecBuffer[3] == MainForm2.si[MainForm2.row] && RecBuffer[4] == 00)
                //        {
                //            MainForm2 mainForm2 = new MainForm2();
                //            mainForm2.textBox1.Text = RecBuffer[2].ToString() + " " + RecBuffer[3].ToString() + " " + "00";
                //            break;
                //        }


                //        for (int i = 0; i < MainForm2.aAddress.Length; i++)
                //        {

                //            int a = Convert.ToInt32(MainForm2.aAddress[i].ToString().Substring(2, 2).PadLeft(2, '0'), 16);
                //            int b = Convert.ToInt32(MainForm2.aAddress[i].ToString().Substring(0, 2));
                //            int c = Convert.ToInt32(MainForm2.aAddress[i].ToString().Substring(4, 2).PadLeft(2, '0'));
                //            if (RecBuffer[1] == 66 && RecBuffer[4] == 0 && RecBuffer[2] == Convert.ToInt32("0x" + MainForm2.Slow[i], 16) && RecBuffer[3] == Convert.ToInt32("0x" + MainForm2.Ssi[i], 16))
                //            {
                //                if (MainForm2.aDataDype[i] == 1)
                //                {
                //                    Righter1 = RecBuffer[5] & 0xff;//低八位
                //                    lefter1 = RecBuffer[6] & 0xff; //高八位
                //                    int16resdata[i] = Convert.ToInt16(lefter1);
                //                    int16resdata[i] <<= 8;
                //                    int16resdata[i] |= Convert.ToInt16(Righter1);
                //                }
                //                else
                //                {
                //                    Righter1 = RecBuffer[5] & 0xff;//低八位
                //                    lefter1 = RecBuffer[6] & 0xff; //高八位
                //                    uint16resdata[i] = Convert.ToUInt16(lefter1);
                //                    uint16resdata[i] <<= 8;
                //                    uint16resdata[i] |= Convert.ToUInt16(Righter1);
                //                    break;
                //                }
                //            }
                //        }
                //        break;
                //    }

                default:
                    break;
            }
        }

        #endregion

        //解码处理
        #region
        private void ReceiveMsgAnalyse1(object data)
        {
            try
            {


                switch (RecBuffer2[0])
                {
                    case 0x5AC:
                        {
                            for (int i = 0; i < MainForm2.aAddress.Length; i++)
                            {

                                //int a = Convert.ToInt32(MainForm2.aAddress[i].ToString().Substring(2, 2).PadLeft(2, '0'), 16);
                                //int b = Convert.ToInt32(MainForm2.aAddress[i].ToString().Substring(0, 2));
                                //int c = Convert.ToInt32(MainForm2.aAddress[i].ToString().Substring(4, 2).PadLeft(2, '0'));
                                if (RecBuffer2[1] == 66 && RecBuffer2[4] == 0 && RecBuffer2[2] == Convert.ToInt32("0x" + MainForm2.Slow[i], 16) && RecBuffer2[3] == Convert.ToInt32("0x" + MainForm2.Ssi[i], 16))
                                {
                                    if (MainForm2.aDataDype[i] == 1)
                                    {
                                        Righter1 = RecBuffer2[5] & 0xff;//低八位
                                        lefter1 = RecBuffer2[6] & 0xff; //高八位
                                        int16resdata[i] = Convert.ToInt16(lefter1);
                                        int16resdata[i] <<= 8;
                                        int16resdata[i] |= Convert.ToInt16(Righter1);
                                    }
                                    else
                                    {
                                        Righter1 = RecBuffer2[5] & 0xff;//低八位
                                        lefter1 = RecBuffer2[6] & 0xff; //高八位
                                        uint16resdata[i] = Convert.ToUInt16(lefter1);
                                        uint16resdata[i] <<= 8;
                                        uint16resdata[i] |= Convert.ToUInt16(Righter1);
                                        break;
                                    }
                                }
                            }
                            break;
                        }

                }
            }
            catch
            { }
            }




        private void ReceiveMsgAnalyse2(object data)
        {
            switch (RecBuffer22[0])
            {
                case 0x5AC:
                    {

                        //连接
                        if (RecBuffer22[1] == 66 && RecBuffer22[2] == 78 && RecBuffer22[3] == 64 && RecBuffer22[4] == 0 && RecBuffer22[5] == 241 && RecBuffer22[6] == 184 && RecBuffer22[7] == 243 && RecBuffer22[8] == 194)
                        {
                            MsgAnalyse6();
                            break;
                        }
                                        
                        break;
                    }
            }
        }
        private void ReceiveMsgAnalyse3(object data)
        {
            switch (RecBuffer3[0])
            {
                case 0x5AC:
                    {
                        for (int i = 0; i < MainForm3.a3Address.Length; i++)
                        {

                            //int a = Convert.ToInt32(MainForm2.aAddress[i].ToString().Substring(2, 2).PadLeft(2, '0'), 16);
                            //int b = Convert.ToInt32(MainForm2.aAddress[i].ToString().Substring(0, 2));
                            //int c = Convert.ToInt32(MainForm2.aAddress[i].ToString().Substring(4, 2).PadLeft(2, '0'));
                            if (RecBuffer3[1] == 66 && RecBuffer3[4] == 0 && RecBuffer3[2] == Convert.ToInt32("0x" + MainForm3.Slow[i], 16) && RecBuffer3[3] == Convert.ToInt32("0x" + MainForm3.Ssi[i], 16))
                            {
                                if (MainForm3.a3DataDype[i] == 1)
                                {
                                    Righter1 = RecBuffer3[5] & 0xff;//低八位
                                    lefter1 = RecBuffer3[6] & 0xff; //高八位
                                    int16resdata[i] = Convert.ToInt16(lefter1);
                                    int16resdata[i] <<= 8;
                                    int16resdata[i] |= Convert.ToInt16(Righter1);
                                }
                                else
                                {
                                    Righter1 = RecBuffer3[5] & 0xff;//低八位
                                    lefter1 = RecBuffer3[6] & 0xff; //高八位
                                    uint16resdata[i] = Convert.ToUInt16(lefter1);
                                    uint16resdata[i] <<= 8;
                                    uint16resdata[i] |= Convert.ToUInt16(Righter1);
                                    break;
                                }
                            }
                        }
                        break;
                    }

            }
        }
        #endregion
        //选择接收的索引 0—IXXAT
        #region
        private void timer_rec_Tick(object sender, EventArgs e)
        {
            //switch (ToolDrpDevType.SelectedIndex)
            //{
            //    case 0:
            //        IXXATReceiveData();
            //        break;
            //    case 1:
            //        ECANReceiveData();
            //        break;
            //}
        }
        #endregion




        //在dataGridView视图上显示
        #region    
        private void timer_view_Tick_1(object sender, EventArgs e)
        {

            SendInterface();

        }
        #endregion

        //数据传输到界面
        #region
        private void SendInterface()
        {
            textBox1.Text = str[1];
            textBox2.Text = str[2];
            textBox3.Text = str[3];
            textBox4.Text = str[4];
            textBox5.Text = str[5];
            textBox6.Text = str[6];
            //
            textBox7.Text = str[8];
            textBox8.Text = str[9];
            textBox9.Text = str[10];
            //
            textBox10.Text = str[12];
            textBox11.Text = str[13];
            textBox12.Text = str[14];
            textBox13.Text = str[15];
            //
            textBox14.Text = str[17];
            textBox15.Text = str[18];
            textBox16.Text = str[19];
            textBox17.Text = str[20];
            textBox18.Text = str[21];
            textBox19.Text = str[22];
            textBox20.Text = str[23];
            //
            textBox21.Text = str[25];
            textBox22.Text = str[26];
            textBox23.Text = str[27];
            textBox24.Text = str[28];
            textBox25.Text = str[29];

            //控制器回复ID
            if (str[34] == "42" && str[35] == "4E" && str[36] == "40" && str[37] == "0" && str[30] == "F1" && str[31] == "B8" && str[32] == "F3" && str[33] == "C2")
            {
                textBox26.Text = str[30] + "\t" + str[31] + "\t" + str[32] + "\t" + str[33];
            }

            else
            {
                textBox26.Text = "";
                //uint16resdata[0]
                //    dgvData[columnIndex][rowsIndex].Value.ToString()
                //    main
            }





        }
        #endregion
        //开始记录
        #region
        private void BtnRecord_Click(object sender, EventArgs e)
        {
            if (BtnRecord.Text == "开始监控" && ToolBtnConnect.Enabled == false)
            {
                timer_view.Enabled = true;
                //timer_rec.Enabled = true;


                if (ToolBtnDisConnect.Enabled == !mConnected)
                {
                    timer_view.Enabled = false;
                }

                BtnRecord.Text = "停止监控";
            }
            else
            {
                BtnRecord.Text = "开始监控";
                //timer_rec.Enabled = false;
                timer_view.Enabled = false;

            }

        }
        #endregion

        //断开连接
        #region
        private void ToolBtnDisConnect_Click(object sender, EventArgs e)
        {
            switch (ToolDrpDevType.SelectedIndex)
            {
                case 0:
                    mConnected = !IXXATClose();
                    break;
                case 1:
                    mConnected = !ECANClose();
                    break;
            }
            if (mConnected)
            { //连接失败
                string msg = TargetClass.GetDiag.Language == TargetClass.CHS ? "通信设备断开失败，请检查原因" : "Communicate disconnect failed，please check the reason";
                MessageBox.Show(msg);
                return;
            }

            ToolDrpBaudrate.Enabled = !mConnected;
            ToolDrpDevType.Enabled = !mConnected;
            ToolBtnConnect.Enabled = !mConnected;
            ToolBtnDisConnect.Enabled = mConnected;
            timer_rec.Enabled = mConnected;
            toolStripDevStatus.Text = TargetClass.GetDiag.Language == TargetClass.CHS ? "未连接" : "Disconnected";
            toolStripDevStatus.ForeColor = Color.Red;
            timer_view.Enabled = false;
        }
        #endregion

        //保存
        #region
        private void BtnSave_Click(object sender, EventArgs e)
        {
            //if (dataGridView.DataSource == null)
            //{
            //    MessageBox.Show("没有数据可以保存");
            //    return;
            //}

            //SaveToExcel(DateTime.Now.ToString("yyyyMMddHHmm")+".csv",dataGridView.DataSource as DataTable);
            //MessageBox.Show("保存成功！\r\n文件已保存至"+Application.StartupPath+@"\Database"+DateTime.Now.ToString("yyyyMMdd")+"文件夹中");

        }
        #endregion
        //保存到excel
        #region
        private void SaveToExcel(string path, DataTable dt)
        {
            try
            {
                //添加文件路径
                string filepath = Application.StartupPath + @"\Database\" + DateTime.Now.ToString("yyyyMMdd");
                //如果没有这个文件就创建
                if (!Directory.Exists(filepath))
                {
                    Directory.CreateDirectory(filepath);
                }
                path = $"{filepath}\\{path}";
                //获取path的路径，给与创建和写入的权力
                FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);
                //允许将字符和字符串写入path，使用filestream创建streamWrite
                StreamWriter sw = new StreamWriter(fs, Encoding.Default);
                //sw.Flush();
                //sw.BaseStream.Seek(0, SeekOrigin.Begin);
                var strline = "";
                //创建列
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    strline += dt.Columns[i].ColumnName;
                    if (i < dt.Columns.Count - 1)
                    {
                        strline += ",";
                    }
                }
                sw.WriteLine(strline);
                //写入行
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    strline = "";
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        strline += dt.Rows[i][j].ToString();
                        if (j < dt.Columns.Count - 1)
                        {
                            strline += ",";
                        }
                    }
                    //写入数据进去文件
                    sw.WriteLine(strline);
                }
                sw.Close();
                sw.Dispose();
                fs.Close();
                fs.Dispose();
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }



        #endregion



        private void OpenForm2()
        {
            
                MainForm2 form2 = new MainForm2();
                form2.ShowDialog();   
        }
        private void OpenForm3()
        {

            MainForm3 form3 = new MainForm3();
            form3.ShowDialog();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            thform2 = new ThreadStart(OpenForm2);//通过ThreadStart委托告诉子线程执行什么方法　　
            Thread threadform2 = new Thread(thform2);
            threadform2.Start();//启动新线程
        }
        private void button2_Click(object sender, EventArgs e)
        {
            thform3 = new ThreadStart(OpenForm3);//通过ThreadStart委托告诉子线程执行什么方法　　
            Thread threadform3 = new Thread(thform3);
            threadform3.Start();//启动新线程
        }

        private void timer_send_Tick(object sender, EventArgs e)
        {

        }

       
    }
}
